package com.liry.security.config;

import com.alibaba.fastjson.JSONArray;
import com.liry.security.domain.entity.Role;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.expression.SecurityExpressionOperations;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author ALI
 * @since 2023/6/15
 */
public class PermissionService extends SecurityExpressionRoot {

    /**
     * Creates a new instance
     *
     * @param authentication the {@link Authentication} to use. Cannot be null.
     */
    public PermissionService(Authentication authentication) {
        super(SecurityContextHolder.getContext().getAuthentication());
    }

    public boolean hasPermission(Object target, String permission) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        CustomUser principal = (CustomUser)authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();

        // 获取权限信息
        Set<String> permissions = new HashSet<>();
//        for (GrantedAuthority authority : authorities) {
//            Object o = cacheManager.get(authority.getAuthority());
//            if (o != null) {
//                List<String> collect = JSONArray.parseArray(o.toString()).stream().map(Object::toString).collect(Collectors.toList());
//                permissions.addAll(collect);
//            }
//        }
//        if (permissions.isEmpty()) {
//            throw new AccessDeniedException("无权限！");
//        }
//        // 判断是否有权限访问
//        String api = servletRequest.getRequestURI();
//        if (!permissions.contains(api)) {
//            throw new AccessDeniedException("无权限！");
//        }

        return authorities.contains(new SimpleGrantedAuthority(permission));
    }
}
